package com.javafactroy.kunlong.bip.icp.message.data.app;

import com.javafactroy.kunlong.bip.icp.message.base.consts.BodyTypeEnum;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.Data;
import lombok.ToString;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

//header (length) + body
//fix header length
@Data
@ToString
public class LengthFieldBytesMsg {
    BodyTypeEnum bodyTypeEnum = BodyTypeEnum.text;
    int length;
    String body;
    int headerLength;
    byte[] byteHeader;
    byte[] byteBody;

    public void decode(ByteBuffer byteBuffer) {
        //LengthFieldMsgDecoder.decode(this, byteBuffer);
    }

    public int buildLength() {
        if (bodyTypeEnum.equals(BodyTypeEnum.bin)) {
            setLength(4 + byteBody.length);
        } else {
            length = 4 + body.length();
        }
        return length;

    }

    public void logHex(byte[] bodys) {

    }

    public ByteBuffer encode() {
        buildLength();
        ByteBuffer byteBuffer = ByteBuffer.allocate(length);
        byteBuffer.putInt(length);

        try {
            if (bodyTypeEnum.equals(BodyTypeEnum.bin)) {
                byteBuffer.put(byteBuffer);
            } else {
                byteBuffer.put(body.getBytes("utf-8"));
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        byteBuffer.rewind();

        return byteBuffer;

    }

    public String toJSONString() {
        return JSON.toJSONString(this, SerializerFeature.PrettyFormat);
    }
}
